#! /usr/bin/perl -w

## Author: Jiahuan Li <huanlf@gmail.com>

use strict;
use Term::ANSIColor qw(:constants);
#$Term::ANSIColor::AUTORESET = 1;

my %nload;
my $mac;

## get ips and its' pkgs,bytes
open (FH, "iptables -L -n -v -t filter|") or die $!;
while (<FH>) {
    next unless /MAC/ and $mac = (split)[-1];
    ($nload{$mac}->{pkts}, $nload{$mac}->{bytes}) = (split)[0,1];
}

## find the mac corresponding to ip
open (FH, "/proc/net/arp" ) or die $!;
while (<FH>) {
    next unless (/eth\d$/);
    $mac = (split)[3];
    next unless exists $nload{$mac};
    next if $mac =~ /^(?:00:){5}00/;
    $nload{$mac}->{ip} = (split)[0];
}

my $i = 0;
for $mac ( sort sort_by_num keys %nload ) {
    $i == 3 ? $i = 1 : $i++;
    $i == 2 ? print GREEN :
    $i == 1 ? print BLUE  :
              print RED   ;
    write;
}
print RESET;

# ---------------------------------------------------- #

## the sort sub
sub sort_by_num {
    my ($x, $y) = ($nload{$a}->{bytes}, $nload{$b}->{bytes});
    ## I ignore G here 
    if ( $x =~ /K$/i ) { $x =~ s/K$//i; $x *= 1024; } elsif ( $x =~ /M$/i ) { $x =~ s/M$//i; $x *= 1024*1024 };
    if ( $y =~ /K$/i ) { $y =~ s/K$//i; $y *= 1024; } elsif ( $y =~ /M$/i ) { $y =~ s/M$//i; $y *= 1024*1024 };

    $y <=> $x;
}

## format output
format STDOUT_TOP =

                          DATA FLOW

     IP                MAC         PKGS   BYTES
----------------------------------------------------
.

format STDOUT =
@<<<<<<<<<<<<  @|||||||||||||||| @>>>>> @>>>>>
$nload{$mac}->{ip} || "0.0.0.0", $mac, $nload{$mac}->{pkts}, $nload{$mac}->{bytes}
.
